﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace ptp3
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }
        protected void Application_Error(object sender, EventArgs e)
        {
            ptp3Entities ptp3db = new ptp3Entities();

            // Get the exception object.
            // Obtain the URL of the request 
            string url = Request.Path;

            // Obtain the Exception object describing the error 
            Exception error = Server.GetLastError();

            //get the inner most exception
            Exception exception;
            for (exception = error; exception.InnerException != null; exception = exception.InnerException) { }
            log l = new log();

            if (exception is HttpException && ((HttpException)exception).GetHttpCode() == 404)
                l.type = "404";
            else
                l.type = "Exception";
            
            l.exception_details = exception.Message + " " + exception.Data;
            l.source_error = exception.Source;
            l.source_file= exception.TargetSite.ToString();
            l.stack_trace = exception.StackTrace;
            l.url = Request.RawUrl.ToString();
            DateTime time = DateTime.Now;              // Use current time
            string format = "yyyy-MM-dd HH:mm:ss";    // Use this format
            l.date = DateTime.Parse(time.ToString(format));  // Write

            ptp3db.AddTolog(l);

            ptp3db.SaveChanges();
        }
    }
}